/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Model.dao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import Model.pojo.*;

/**
 *
 * @author Ariane
 */
public class CompraDao implements InterfaceCompraDao{
	private File arquivo = new File("ListaCompra.txt");
	private ArrayList<Compra> lista = new ArrayList<Compra>();
	private long codigo;
	private double preco;
	private Compra compra;
	
	private FileWriter fw;
	private BufferedWriter bw;
	private FileReader fr;
	private BufferedReader br;
	Iterator<Integer> quant;
	Iterator<Item> it2;
	Iterator<Compra> it;
	
	public ArrayList<Compra> ler() throws IOException{
		fr = new FileReader (arquivo);
		br = new BufferedReader (fr);
		while (br.ready()){
			codigo = Long.parseLong(br.readLine());
			preco = Double.parseDouble(br.readLine());
			inserir(codigo, preco);
		}
		br.close();
		fr.close();
		return lista;
	}
	
	public void inserir (long codigo, double preco){
		compra = new Compra(codigo, preco);
		lista.add(compra);
	}
	
	//Salva uma compra no arquivo ListaCompra.
	public boolean salvar(Compra compra) throws IOException{
		if (compra == null) return false;
		fw = new FileWriter(arquivo, true);
		bw = new BufferedWriter (fw);
		bw.write(""+compra.getCodigo());
		bw.newLine();
		bw.write(""+compra.getPreco());
		bw.newLine();
		bw.close();
		fw.close();
		return true;
	}
	
	public boolean salvar(ArrayList<Compra> lista) throws IOException{
				if (lista.isEmpty() == true) return false;
				fw = new FileWriter(arquivo);
				it = lista.iterator();
				while (it.hasNext()){
					salvar(it.next());
				}
				return true;
			}
	
	public boolean realizarCompra(Pedido pedido){
		if (pedido == null) return false;
		inserir(pedido.getCodigo(),setarValorCompra(pedido));
		return true;
	}
	
	public double setarValorCompra (Pedido pedido){
		double valor = 0;
		it2 = pedido.getItens().iterator();
		quant = (Iterator<Integer>) pedido.getQuantidades();
		while (it2.hasNext() && quant.hasNext()){
			valor = (double) (valor +((Item) it2.next()).getPrecoCusto()*((Item) it2.next()).getMargemLucro()*quant.next());
		}
		return valor;
	}
	public long gerarCodigo (){
		if (lista.isEmpty() == true) return 1;
		return (lista.get(lista.size()-1).getCodigo())+1;
	}
}

	

